import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'
import { login } from '@/api/user'
import { addCart } from '../api/cart'
// import user from './user'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    user: {},
    cart: [],
    token: ''
  },
  getters: {
    //返回token
    getToken(state) {
      if (state.token == '' || Object.keys(state.user).length == 0) {
        return false
      }
      return state.token
    },
    //返回用户信息
    getUser(state) {
      if (Object.keys(state.user).length == 0) {
        return false
      }
      return state.user
    },
    //返回购物车信息
    getCart(state) {
      if (state.cart.length == 0) {
        return false
      }
      return state.cart
    }
  },
  mutations: {
    //修改token
    setToken(state, val) {
      state.token = val
    },
    //修改用户信息
    setUser(state, val) {
      state.user = val
    },
    //获取购物车商品
    setCart(state, val) {
      state.cart = val
    },
    //删除购物车商品
    delGoods(state, cid) {
      let index = state.cart.findIndex((item) => item.cid == cid)
      if (index >= 0) {
        state.cart.splice(index, 1)
      }
    },
    //修改数量
    setNumber(state, obj) {
      let index = state.cart.findIndex((item) => item.cid == obj.cid)
      if (index >= 0) {
        state.cart[index].number = obj.number
      }
    }
  },
  actions: {
    //登录
    async handleLogin(context, params) {
      let {
        data: { cart, data, token, code }
      } = await login(params)
      return new Promise((resolve, reject) => {
        if (code == 200) {
          context.commit('setToken', token)
          localStorage.setItem('token', token)
          context.commit('setUser', data)
          context.commit('setCart', cart)
          resolve(true)
        }
        reject(false)
      })
    },
    //退出登录
    handleLogOut(context) {
      context.commit('setToken', '')
      localStorage.removeItem('token')
      context.commit('setUser', {})
      context.commit('setCart', [])
    },
    //添加购物车
    async cartActions({ commit }, params) {
      let {
        data: { data, code }
      } = await addCart(params)
      if (code == 200) {
        commit('setCart', data)
      } else {
        console.log('失败')
      }
    }
  },
  modules: {},
  plugins: [
    createPersistedState({
      key: 'store',
      render(state) {
        return { ...state }
      }
    })
  ]
})
